﻿#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

import wx
import os
import wx.stc as stc
from core.ide.langsmanager import LangsManager
from core.ui.centralpanel import CentralPage
from core.ide.commandmanager import CommandManager
from core.utils.cmdenum import UPDATE_SETTINGS
from core.ide.datamangager import DataMangager
from core.ui.mainframe import MainFrame
from completion import AutoCompletion

font = 'face:Courier New,size:9'
font = wx.Font( 10, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL )
#font = wx.Font( 10, wx.FONTFAMILY_SCRIPT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL )



class Wysiwyg(stc.StyledTextCtrl):
    def __init__(self,parent):
        #if file_:
        #    CentralPage.__init__(self,os.path.basename(file_),file_)
        #else:
        #    CentralPage.__init__(self)

        
        self._comp=None
        self._id=wx.NewId()
        self._isModified=-1
        self._lang=None

        stc.StyledTextCtrl.__init__(self,parent,self._id,style=wx.NO_BORDER)
        
        panel=wx.Panel(parent,-1)
        CommandManager().listener(UPDATE_SETTINGS,self.setConfig)

        self.SetModEventMask(stc.STC_MOD_INSERTTEXT | stc.STC_MOD_DELETETEXT )
        self.Bind(wx.EVT_KEY_DOWN, self.onKeyPressed)
        self.Bind(wx.stc.EVT_STC_MODIFIED,self.onModified)
        self.setConfig()
    
    
    def setFile(self,file_):
        self.file=file_
        self.SetCodePage( wx.stc.STC_CP_UTF8 )
        self.setLang(LangsManager().getLangFromFile(file_))
        self.LoadFile( file_ )
        self.SetSelection(0,0)
        
    
    def setConfig(self):
        self.SetMarginType(1,stc.STC_MARGIN_NUMBER)
        self.SetMarginType(0,stc.STC_MARGIN_SYMBOL)
        #self.SetMarginLeft(100)
        #self.SetMargins(1,0)
        self.SetMarginWidth(0,15)
        self.SetMarginWidth(1,22)
        self.SetBackSpaceUnIndents(1)
        self.SetViewWhiteSpace(self.getSetting("Show White Space",False))
        self.SetAutoLayout(False)
        self.SetTabIndents(self.getSetting("Tab indent",4))
        #self.SetTabWidth(20)
        self.SetIndent(self.getSetting("Space indent",4))   #indent space
        print ("Repleace tab by space", self.getSetting("Repleace tab by space",False))
        self.SetUseTabs(not self.getSetting("Repleace tab by space",False))
        print self.GetUseTabs()
        self.SetIndentationGuides(self.getSetting("Show Indentation Guides",False))
        self.AutoCompSetIgnoreCase(self.getSetting("Auto Completion ignore case",True))
        self.AutoCompSetAutoHide(0)
    
    def getSetting(self,name,defaultValue):
        if self._lang:
            sects=[self._lang.name,"Editor"]
        else:
            sects=["Editor"]
        return DataMangager().getDataInSections(sects,name,defaultValue,None,'Wysiwyng').value
    
    def enable(self):
        CentralPage.enable(self)
        if  self._lang:
            self._lang.read(self.GetText(),self.file)
        
    def save(self):
        if self._isModified<1:
            return
        self.Parent.setTabTitle(self.Parent.getTabTitle()[:-1])

        self._isModified=0
        #f=open(self.file,'w')
        #f.write(self.GetTextUTF8())
        #f.close()
        self.SaveFile( self.file )
    
    def getLang(self):
        return self._lang
    
    def setLang(self,lang):
        self._lang=lang
        if hasattr(self._lang, "getFileTabName"):
            t=self._lang.getFileTabName(self.file)
            self.Parent.setTabTitle(t)
        if self._lang:
            print(self._lang.name)
            self._lang.read(self.GetText(),self.file)
            self.applyStyle()
            if hasattr(self._lang, "getKeyWord"):
                self.applyKeyWords()
            self.setConfig()
        
    def applyStyle(self):
        if not self._lang:
            return
        self.SetLexer(self._lang.getLexer())
        styles=self._lang.getStyles()
        for ind in styles:
            self.StyleSetFont(ind, font)
            self.StyleSetSpec(ind,styles[ind])
            
        
    def applyKeyWords(self):
        keywords=self._lang.getKeyWord()
        for ind in keywords:
            self.SetKeyWords(ind," ".join(keywords[ind]))
            
    def setText(self, text, lang=None):
        self.setLang(lang)
        self.SetTextUTF8(text)
        
        self.GetText()
        self.setConfig()
    
    def onKeyPressed(self, e):
        if self.CallTipActive():
            self.CallTipCancel()
        key = e.GetKeyCode()
        print key
        
        if self._comp:
            if key == 13 or key == 370 or key == 316:
                self._comp.validate()
            elif key == 315:
                self._comp.goUp()
            elif key == 317:
                #event.Skip()
                print "down"
                self._comp.goDown()
            elif event.GetUnicodeKey()==0:
                self.closeAutoCompletion()
            else:
                e.Skip()
        else:
            if key == 32 and e.ControlDown():
                self.SetCurrentPos(self.GetCurrentPos())   
                if not self.openAutoCompletion():
                    e.Skip()
            elif key==13 or key==370:
                if self.GetUseTabs():
                    add="\n"+"\t"*self.GetLineIndentation(self.GetCurrentLine()/self.GetTabWidth())
                else:
                    add="\n"+" "*self.GetLineIndentation(self.GetCurrentLine())
                self.InsertText(self.GetCurrentPos(),add)
                p=self.GetCurrentPos()+len(add)
                self.SetSelection(p,p)
            else:
                e.Skip()

    def onModified(self,e):

        if not self._isModified:
            self.Parent.setTabTitle(self.Parent.getTabTitle()+"*")
        if self._isModified<1:
            self._isModified+=1
        
        #if self._comp:
        #    self.updateAutoCompletionWord()
        
        if e.GetLinesAdded():
            self._lang.read(self.GetText(),self.file)            
        if e.GetText()=="." and self.GetTextRange(self.GetCurrentPos(),self.GetCurrentPos()+1)==".":
            
            self.SetCurrentPos(self.GetCurrentPos()+1)   
            if not self.openAutoCompletion():
                e.Skip()
    
    def updateAutoCompletionWord(self):
        line = self.GetTextRange(self.PositionFromLine(self.GetCurrentLine()), self.GetCurrentPos()+1)
        sep = "["+self._lang.getSeparator()+"]"
        print ("sep",sep)
        word=re.split(sep,line)[-1]
        print (word,re.split(sep,line))
        self._comp.setWord(word)
        
    def openAutoCompletion(self):
        line=self.GetTextRange(self.PositionFromLine(self.GetCurrentLine()),self.GetCurrentPos())
        completion=self._lang.getCompletion(self.GetCurrentLine(),line)
        #print completion
        if len(completion):
            pos = self.PointFromPosition(self.GetCurrentPos())
            pos.y += self.TextHeight(self.GetCurrentLine())
            self._comp = AutoCompletion(self.Parent,pos+self.GetScreenPosition(),self)
            self._comp.setList(completion,None)
            self._comp.open()
            #self.SetFocus()
            self._comp.list.Bind(wx.EVT_KILL_FOCUS,self.closeAutoCompletion)
            self._startComp=self.GetCurrentPos()
            return True
        return False
                
    def insertWord(self,text,close=False):
        self.SetSelection(self._startComp,self.GetCurrentPos())
        self.ReplaceSelection(text)
        #self.SetSelection(self.GetCurrentPos()+len(text),self.GetCurrentPos()+len(text))
        if close:
            self.closeAutoCompletion()
    
    def insertKeyEvent(self,e):
        #print(e.GetKeyCode())
        if e.GetKeyCode()==8:
            self.CmdKeyExecute(stc.STC_CMD_DELETEBACK)
        else:
            code=e.GetUnicodeKey()
            if code:
                char=unichr(e.GetUnicodeKey())
                self.InsertText(self.GetCurrentPos(),char)
                self.SetSelection(self.GetCurrentPos()+1,self.GetCurrentPos()+1)
                if char==".":
                    self.closeAutoCompletion()
                    self.openAutoCompletion()
        self._comp.setWord(self.GetTextRange(self._startComp,self.GetCurrentPos()))

    def closeAutoCompletion(self,e=None):
        self._comp.list.Unbind(wx.EVT_KILL_FOCUS)
        self._comp.destroy()
        self._comp=None
        self.SetFocus()

